package com.wskj.ws.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import javax.websocket.Session;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 管理全局Channel以及用户对应的channel（推送消息）
 */
@Slf4j
public class WebSocketUser {

    /**
     * 存放请求ID与session的对应关系
     */
    private static volatile ConcurrentHashMap<String, WebSocket> sessionMap = null;

    /**
     * 定义三把锁
     */
    private static final Object lock1 = new Object();

    public static ConcurrentHashMap<String, WebSocket> getSessionMap() {
        if (null == sessionMap) {
            synchronized (lock1) {
                if (null == sessionMap) {
                    sessionMap = new ConcurrentHashMap<>();
                }
            }
        }
        return sessionMap;
    }

    public static WebSocket getSession(String userId) {
        if (null == sessionMap) {
            return getSessionMap().get(userId);
        }
        return sessionMap.get(userId);
    }

    /**
     * 移出用户
     * @param key 键
     */
    public static boolean removeUser(String key) {
        log.info("正在移出用户 - {}", key);
        WebSocket webSocket = sessionMap.remove(key);
        if (webSocket != null) {
            boolean containsKey = sessionMap.containsKey(key);
            log.info("移出结果 - {}", containsKey ? "失败" : "成功","当前在线人数-{}",sessionMap.size());
            return containsKey;
        } else {
            return true;
        }
    }

    /**
     * 群发消息文本消息
     * @param message 消息内容
     */
    public static void sendMessageToUsersByText(String message) {
        Collection<WebSocket> values = sessionMap.values();
        for (WebSocket webSocket : values) {
            sendMessageToUserByText(webSocket.getSession(), message);
        }
    }

    /**
     * 发送文本消息
     * @param session 自己的用户名
     * @param message  消息内容
     */
    public static void sendMessageToUserByText(WebSocketSession session, String message) {
        if (session != null) {
            try {
                session.sendMessage(new TextMessage(message));
            } catch (IOException e) {
                log.error("\n[发送消息异常]", e);
            }
        } else {
            log.info("\n[你已离线]");
        }
    }
}

